package com.ruoyi.system.service.impl;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SjElecCost;
import com.ruoyi.system.domain.SjMeterReading;
import com.ruoyi.system.domain.SysFloor;
import com.ruoyi.system.domain.TenantInfo;
import com.ruoyi.system.mapper.ElecCostMapper;
import com.ruoyi.system.mapper.ElecMeterMapper;
import com.ruoyi.system.service.IElecCostService;
import com.ruoyi.system.service.IElecMeterService;
import com.ruoyi.system.service.ISysFloorService;
import com.ruoyi.system.service.ITenantInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ElecCostServiceImpl implements IElecCostService {

    @Autowired
    private ElecCostMapper elecCostMapper;

    @Autowired
    private ITenantInfoService tenantInfoService;

    @Autowired
    private ISysFloorService sysFloorService;

    @Autowired
    private ElecMeterMapper elecMeterMapper;

    @Override
    public List<SjElecCost> selectElecCostList(SjElecCost sjElecCost) {
        return elecCostMapper.selectElecCostList(sjElecCost);
    }

    @Override
    public AjaxResult generateElec(String etldt, List<SysFloor> floorInfos) {
        StringBuilder message = new StringBuilder();
        for(SysFloor sysFloor:floorInfos){
            SjMeterReading sjMeterReading = new SjMeterReading();
            sjMeterReading.setEtldt(etldt);
            sjMeterReading.setFloorName(sysFloor.getFloorName());
            SjMeterReading sjmr = elecMeterMapper.selectElecMeterByFloorAndEtldt(sjMeterReading);
            if (sjmr == null) {
                message.append("缺少"+etldt+"批次"+sysFloor.getFloorName()+"楼层的抄表记录</br>");
                continue;
            }
            TenantInfo tenantInfo = new TenantInfo();
            tenantInfo.setTenantFloor(sysFloor.getFloorName());
            List<TenantInfo> tenantInfos = tenantInfoService.selectTenantInfoList(tenantInfo);
            if(tenantInfos!=null&&tenantInfos.size()>1){  //判断楼层是否只有一个租户
                //需要公摊
                if(sjmr.getDegreeIssueD()>0){
                    //有D表
                    Double allElec;
                    if("1".equals(sysFloor.getFloorName())){  //一楼特殊处理
                        allElec = sjmr.getDegreeA()+sjmr.getDegreeB()+sjmr.getDegreeC() - sjmr.getDegreeD();  //A,B,C公摊用电量
                    }else{
                        allElec = sjmr.getDegreeA()+sjmr.getDegreeB()+sjmr.getDegreeC();  //A,B,C公摊用电量
                    }
                    Double allArea = tenantInfoService.selectSumFloorArea(sysFloor.getFloorName());  //楼层总面积
                    Double DArea = 0.0;
                    for(TenantInfo ti:tenantInfos){
                        if("3".equals(ti.getAmmeter())){   //该租户有且仅有D表
                            DArea = ((ti.getTenantArea()==null)?0.00:ti.getTenantArea().doubleValue()) + ((ti.getEmptyArea()==null)?0.00:ti.getEmptyArea().doubleValue());   //获取D表租户面积
                        }
                    }
                    Double poolArea = allArea - DArea;  //公摊面积 = 楼层总面积 - D表专用租户
                    for(TenantInfo ti:tenantInfos){
                        Double tenantElec;
                        if(!"3".equals(ti.getAmmeter())){   //判断该租户有且仅有D表
                            Double tenantArea = ((ti.getTenantArea()==null)?0.00:ti.getTenantArea().doubleValue()) + ((ti.getEmptyArea()==null)?0.00:ti.getEmptyArea().doubleValue());
                            tenantElec = tenantArea/poolArea*allElec; //普通租户用电量
                        }else{
                            tenantElec = sjmr.getDegreeD(); //D表专用租户用电量
                        }
                        insertElecCost(sysFloor,ti,tenantElec,etldt);
                    }
                }else{
                    //没有D表，直接公摊
                    Double allElec = sjmr.getDegreeA()+sjmr.getDegreeB()+sjmr.getDegreeC();
                    Double allArea = tenantInfoService.selectSumFloorArea(sysFloor.getFloorName());  //楼层总面积
                    for(TenantInfo ti:tenantInfos){
                        Double tenantArea = ((ti.getTenantArea()==null)?0.00:ti.getTenantArea().doubleValue()) + ((ti.getEmptyArea()==null)?0.00:ti.getEmptyArea().doubleValue());
                        Double tenantElec;
                        if(allArea==0.0){
                            tenantElec = 0.0;
                        }else {
                            tenantElec = tenantArea/allArea*allElec;
                        }
                        insertElecCost(sysFloor,ti,tenantElec,etldt);
                    }
                }
            }else{
                //楼层单租户
                if(tenantInfos.size()==1){  //楼层有租户
                    TenantInfo tenant = tenantInfos.get(0);
                    Double allElec = sjmr.getDegreeA()+sjmr.getDegreeB()+sjmr.getDegreeC()+sjmr.getDegreeD();
                    insertElecCost(sysFloor,tenant,allElec,etldt);
                }
            }
        }
        if(StringUtils.isEmpty(message.toString())){
            return AjaxResult.success();
        }else{
            return AjaxResult.success("操作成功</br>"+message.toString());
        }
    }

    @Override
    public int deleteElecByEtldt(String etldt) {
        return elecCostMapper.deleteElecByEtldt(etldt);
    }

    @Override
    public String importElecCost(List<SjElecCost> sjElecCostList) {
        int size = 0;
        if(sjElecCostList!=null){
            size = sjElecCostList.size();
        }
        int errorData = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        StringBuilder errorDatas = new StringBuilder();
        String etldt = "";
        DecimalFormat dec = new DecimalFormat("#0.00");
        if(sjElecCostList!=null&&sjElecCostList.size()>0){
            try {
                etldt = sjElecCostList.get(0).getEtldt();
                sdf.parse(etldt);
            } catch (ParseException e) {
                throw new BusinessException("日期格式不正确");
            }
            //删除之前数据  重新生成？
            elecCostMapper.deleteElecByEtldt(etldt);
        }
        int count = 1;
        String tempFloor = "";
        for(SjElecCost sjElecCost:sjElecCostList){
            count++;
            try {
                sdf.parse(sjElecCost.getEtldt());
            } catch (ParseException e) {
                errorData++;
                String errStr = "第"+count+"行,缺少电费批次或日期格式不正确；</br>";
                errorDatas.append(errStr);
                continue;
            }
            if(!etldt.equals(sjElecCost.getEtldt())){
                errorData++;
                String errStr = "第"+count+"行,日期不统一；</br>";
                errorDatas.append(errStr);
                continue;
            }
            if(StringUtils.isEmpty(sjElecCost.getFloorName())){
                if(StringUtils.isEmpty(tempFloor)){
                    errorData++;
                    String errStr = "第"+count+"行,未填写楼层；</br>";
                    errorDatas.append(errStr);
                    continue;
                }else{
                    sjElecCost.setFloorName(tempFloor);
                }
            }else{
                if("合计".equals(sjElecCost.getFloorName())){
                    continue;
                }
                tempFloor = sjElecCost.getFloorName();
            }
            if(StringUtils.isEmpty(sjElecCost.getTenantName())){
                errorData++;
                String errStr = "第"+count+"行,未填写租户；</br>";
                errorDatas.append(errStr);
                continue;
            }
            if(sjElecCost.getDegreeUsed()==null){
                sjElecCost.setDegreeUsed(0.0);
            }
            SysFloor sysFloor = sysFloorService.selectSysFloorByName(sjElecCost.getFloorName());
            if(sysFloor==null){
                errorData++;
                String errStr = "第"+count+"行,未找到楼层"+sjElecCost.getFloorName()+"；</br>";
                errorDatas.append(errStr);
                continue;
            }
            String properElecCoef = sysFloor.getProperElecCoef(); //电费系数
            if(StringUtils.isEmpty(properElecCoef)){
                errorData++;
                String errStr = "第"+count+"行,楼层"+sjElecCost.getFloorName()+"缺少物业电系数；</br>";
                errorDatas.append(errStr);
                continue;
            }
            Double tenantElec = sjElecCost.getDegreeUsed();
            if("新风机房".equals(sjElecCost.getTenantName())||"餐厅".equals(sjElecCost.getTenantName())||"洗车场".equals(sjElecCost.getTenantName())){
                if(sjElecCost.getLightDegree() == null){
                    Double lightDegree = tenantElec;
                    sjElecCost.setLightDegree(lightDegree);
                }
                if(sjElecCost.getLightCost() == null){
                    Double lightCost = Double.valueOf(properElecCoef)*sjElecCost.getLightDegree();
                    lightCost = Double.valueOf(dec.format(lightCost));
                    sjElecCost.setLightCost(lightCost);
                }
            }else{
                String lightParam = sysFloor.getSunElecParam(); //照明电量系数
                String powerBatteryParam = sysFloor.getPowerBatteryParam(); //动力电量系数
                if(StringUtils.isEmpty(lightParam)){
                    errorData++;
                    String errStr = "第"+count+"行,楼层"+sjElecCost.getFloorName()+"缺少照明电量系数；</br>";
                    errorDatas.append(errStr);
                    continue;
                }
                if(StringUtils.isEmpty(powerBatteryParam)){
                    errorData++;
                    String errStr = "第"+count+"行,楼层"+sjElecCost.getFloorName()+"缺少动力电量系数；</br>";
                    errorDatas.append(errStr);
                    continue;
                }
                if(sjElecCost.getLightDegree() == null){
                    Double lightDegree = tenantElec*(Double.parseDouble(lightParam));
                    lightDegree = Double.valueOf(dec.format(lightDegree));
                    sjElecCost.setLightDegree(lightDegree);
                }
                if(sjElecCost.getLightCost() == null){
                    Double lightCost = Double.valueOf(properElecCoef)*sjElecCost.getLightDegree();
                    lightCost = Double.valueOf(dec.format(lightCost));
                    sjElecCost.setLightCost(lightCost);
                }
                if(sjElecCost.getPowerDegree() == null){
                    Double powerDegree = Double.valueOf(powerBatteryParam)*sjElecCost.getLightDegree();
                    powerDegree = Double.valueOf(dec.format(powerDegree));
                    sjElecCost.setPowerDegree(powerDegree);
                }
                if(sjElecCost.getPowerCost() == null){
                    Double powerCost = Double.valueOf(properElecCoef)*sjElecCost.getPowerDegree();
                    powerCost = Double.valueOf(dec.format(powerCost));
                    sjElecCost.setPowerCost(powerCost);
                }
            }
            sjElecCost.setCreateTime(new Date());
            sjElecCost.setElecId(UUID.randomUUID().toString().replaceAll("-",""));
            sjElecCost.setNum(count-1);
            elecCostMapper.insertElecCost(sjElecCost);
        }
        String message;
        if(size>0){
            message = "共导入"+size+"条数据。</br>";
        }else{
            return "无数据";
        }
        if(StringUtils.isNotEmpty(errorDatas.toString())){
            message = message + "其中" + errorData + "条数据导入失败，错误原因如下：</br>";
            message = message + errorDatas.toString();
        }
        return message;
    }

    @Override
    public List<SjElecCost> exportElecCost(SjElecCost sjElecCost) {
        List<SjElecCost> list = elecCostMapper.selectElecCostList(sjElecCost);
        SjElecCost sumSjElecCost = new SjElecCost();
        sumSjElecCost.setFloorName("合计");
        Double degreeUsed = 0.0;
        Double lightDegree = 0.0;
        Double lightCost = 0.0;
        Double powerDegree = 0.0;
        Double powerCost = 0.0;
        for(SjElecCost sjec:list){
            if(sjec.getDegreeUsed()!=null){
                degreeUsed += sjec.getDegreeUsed();
            }
            if(sjec.getLightDegree()!=null){
                lightDegree += sjec.getLightDegree();
            }
            if(sjec.getLightCost()!=null){
                lightCost += sjec.getLightCost();
            }
            if(sjec.getPowerDegree()!=null){
                powerDegree += sjec.getPowerDegree();
            }
            if(sjec.getPowerCost()!=null){
                powerCost += sjec.getPowerCost();
            }
        }
        sumSjElecCost.setDegreeUsed(degreeUsed);
        sumSjElecCost.setLightDegree(lightDegree);
        sumSjElecCost.setLightCost(lightCost);
        sumSjElecCost.setPowerDegree(powerDegree);
        sumSjElecCost.setPowerCost(powerCost);
        if(list!=null){
            list.add(sumSjElecCost);
        }
        return list;
    }

    public void insertElecCost(SysFloor sysFloor,TenantInfo tenant,Double tenantElec,String etldt){
        SjElecCost sjElecCost = new SjElecCost();
        sjElecCost.setFloorName(tenant.getTenantFloor());
        sjElecCost.setTenantId(tenant.getTenantId());
        sjElecCost.setTenantName(tenant.getTenantName());
        sjElecCost.setEtldt(etldt);
        sjElecCost.setElecId(UUID.randomUUID().toString().replaceAll("-",""));
        if(!tenant.getCharges().contains("2")){
            //租户的费用不需要收费
            tenantElec = 0.0;
        }
        //收费系统默认为1
        Double chargeCoe = 1.0;
        if(tenant.getChargeCoefficient()!=null){
            chargeCoe = tenant.getChargeCoefficient();
        }
        sjElecCost.setDegreeUsed(tenantElec);
        //获取照明系数  动力系数  计算照明电量，动力电量，照明费用，动力费用
        //TODO
        DecimalFormat dec = new DecimalFormat("#0.00");
        String lightParam = sysFloor.getSunElecParam(); //照明电量系数
        String powerBatteryParam = sysFloor.getPowerBatteryParam(); //动力电量系数
        String properElecCoef = sysFloor.getProperElecCoef(); //电费系数
        Double tenantArea = ((tenant.getTenantArea()==null)?0.00:tenant.getTenantArea().doubleValue()) + ((tenant.getEmptyArea()==null)?0.00:tenant.getEmptyArea().doubleValue());
        if(tenantArea!=0.0){  //面积不为空
            //照明电量 = 用电量 * 照明电量系数
            Double lightDegree = tenantElec*(Double.parseDouble(lightParam));
            lightDegree = Double.valueOf(dec.format(lightDegree));
            //照明费用 = 照明电量 * 电费系数
            Double lightCost = Double.valueOf(properElecCoef)*lightDegree*chargeCoe;
            lightCost = Double.valueOf(dec.format(lightCost));
            //动力电量 = 照明电量 * 动力电量系数
            Double powerDegree = Double.valueOf(powerBatteryParam)*lightDegree;
            if(!tenant.getCharges().contains("3")){
                powerDegree = 0.0;
            }else{
                powerDegree = Double.valueOf(dec.format(powerDegree));
            }
            //动力费用 = 动力电量 * 电费系数
            Double powerCost = Double.valueOf(properElecCoef)*powerDegree*chargeCoe;
            powerCost = Double.valueOf(dec.format(powerCost));
            sjElecCost.setLightDegree(lightDegree);
            sjElecCost.setLightCost(lightCost);
            sjElecCost.setPowerDegree(powerDegree);
            sjElecCost.setPowerCost(powerCost);
        }else{  //没有面积  照明电量==用电量
            Double lightDegree = tenantElec;
            Double lightCost = Double.valueOf(properElecCoef)*lightDegree*chargeCoe;
            lightCost = Double.valueOf(dec.format(lightCost));
            sjElecCost.setLightDegree(lightDegree);
            sjElecCost.setLightCost(lightCost);
            sjElecCost.setPowerDegree(0.0);
            sjElecCost.setPowerCost(0.0);
        }
        sjElecCost.setCreateTime(new Date());
        elecCostMapper.insertElecCost(sjElecCost);
    }
}
